package com.chunxuan.langquan.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chunxuan.langquan.MainActivity;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.LqProvinceBean;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.ui.listener.MyOrientationListener;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class GradeActivity extends Base2Activity {
    private RadioGroup rgHighSchool,rgMiddleSchool,rgPrimarySchool,rgPrimarySchool2;
    private int grade_category_id=666151;//年级id
    private boolean isChecked = false;
    private TextView tvConfirm;
    private LinearLayout llSelectCity;
    private TextView tvSelectCity;
    private List<LqProvinceBean> lqProvinceBeanList=new ArrayList<>();
    private String mergename;
    private String pro,city,area;
    //百度地图-获取定位
    private LocationClient mylocationClient;//定位服务客户对象
    private MylocationListener mylistener;//重写的监听类
    private int count=0;
    private MyOrientationListener myOrientationListener;//方向感应器类对象
    private boolean selectLocation=false;
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_select_grade;
    }
    private Disposable getProvList() {
        return APIRetrofit.getDefault().getProvList(Global.HEADER,"")
                .compose(RxUtil.<BaseResult2<List<LqProvinceBean>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<LqProvinceBean>>>() {
                    @Override
                    public void accept(BaseResult2<List<LqProvinceBean>> result2) throws Exception {
                        hideProgress();
                        if(result2.isSuccess()){
                            lqProvinceBeanList=result2.getData();
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取省份列表失败");
                    }
                });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rgHighSchool=findViewById(R.id.rg_high_school);
        rgMiddleSchool=findViewById(R.id.rg_middle_school);
        rgPrimarySchool=findViewById(R.id.rg_primary_school);
        rgPrimarySchool2=findViewById(R.id.rg_primary_school2);
        tvConfirm=findViewById(R.id.tv_ok);
        llSelectCity=findViewById(R.id.ll_select_city);
        tvSelectCity=findViewById(R.id.tv_select_city);
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
        initLocation();
        Intent intent=getIntent();
        if(null!=intent) {
            mergename = intent.getStringExtra("mergename");
            if(!TextUtils.isEmpty(mergename)){
                String[] mergenameList=mergename.split(",");
                pro=mergenameList[1];
                city=mergenameList[2];
                area=mergenameList[3];
//                tvSelectCity.setText(mergename.replace("中国","").replaceAll(",",""));
                selectLocation=true;
                tvSelectCity.setText(pro+city+area);
            }
        }
        getProvList();
        llSelectCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("lqProvinceBeanList", (Serializable) lqProvinceBeanList);
                bundle.putString("from","年级");
                Intent intent = new Intent(GradeActivity.this, SelectProvinceActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(grade_category_id==666151){
                    ToastUtils.showShort("请选择年级");
                    return;
                }
                if(TextUtils.isEmpty(pro)||TextUtils.isEmpty(city)||TextUtils.isEmpty(area)){
                    ToastUtils.showShort("请选择城市");
                }else{
                    editGradeAndCity();
                }

            }
        });
        rgHighSchool.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (isChecked) return;
                if(group.getId()==R.id.rg_high_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_middle_school){
                    isChecked=true;
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school2){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    isChecked=false;
                }
                switch (checkedId){
                    case R.id.rb_high_school_class1:
                        grade_category_id=13;
                        break;
                    case R.id.rb_high_school_class2:
                        grade_category_id=14;
                        break;
                    case R.id.rb_high_school_class3:
                        grade_category_id=15;
                        break;
                }
                return;
            }
        });
        rgMiddleSchool.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (isChecked) return;
                if(group.getId()==R.id.rg_high_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_middle_school){
                    isChecked=true;
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school2){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    isChecked=false;
                }
                switch (checkedId){
                    case R.id.rb_middle_school_class1:
                        grade_category_id=10;
                        break;
                    case R.id.rb_middle_school_class2:
                        grade_category_id=11;
                        break;
                    case R.id.rb_middle_school_class3:
                        grade_category_id=12;
                        break;
                }
                return;
            }
        });
        rgPrimarySchool.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (isChecked) return;
                if(group.getId()==R.id.rg_high_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_middle_school){
                    isChecked=true;
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school2){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    isChecked=false;
                }
                switch (checkedId){
                    case R.id.rb_primary_class1:
                        grade_category_id=4;
                        break;
                    case R.id.rb_primary_class2:
                        grade_category_id=5;
                        break;
                    case R.id.rb_primary_class3:
                        grade_category_id=6;
                        break;
                }
                return;
            }
        });
        rgPrimarySchool2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (isChecked) return;
                if(group.getId()==R.id.rg_high_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_middle_school){
                    isChecked=true;
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool2.clearCheck();
                    isChecked=false;
                }else if(group.getId()==R.id.rg_primary_school2){
                    isChecked=true;
                    rgMiddleSchool.clearCheck();
                    rgHighSchool.clearCheck();
                    rgPrimarySchool.clearCheck();
                    isChecked=false;
                }
                switch (checkedId){
                    case R.id.rb_primary_class4:
                        grade_category_id=7;
                        break;
                    case R.id.rb_primary_class5:
                        grade_category_id=8;
                        break;
                    case R.id.rb_primary_class6:
                        grade_category_id=9;
                        break;
                }
                return;
            }
        });
    }
    private void editGradeAndCity() {
        APIRetrofit.getDefault().editGradeAndCity(Global.HEADER, grade_category_id,pro,city,area)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        Arad.preferences.putBoolean("editGradeSuccess",true).flush();

                        if(Global.IS_SHOW==1){
                            startActivity(GuidActivity.class);
                            finish();
                        }else if(Global.IS_SHOW==0){
                            Intent intent=new Intent(GradeActivity.this, MainActivity.class);
                            intent.putExtra("guid_id",0);
                            startActivity(intent);
                            finish();
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("修改年级失败");
                    }
                });
    }

    private void initLocation() {
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        mylocationClient = new LocationClient(this);
        mylistener = new MylocationListener();

        //注册监听器
        mylocationClient.registerLocationListener(mylistener);
        //配置定位SDK各配置参数，比如定位模式、定位时间间隔、坐标系类型等
        LocationClientOption mOption = new LocationClientOption();
        //设置坐标类型
        mOption.setCoorType("bd09ll");
        //设置是否需要地址信息，默认为无地址
        mOption.setIsNeedAddress(true);
        //设置是否打开gps进行定位
        mOption.setOpenGps(true);
        //设置扫描间隔，单位是毫秒 当<1000(1s)时，定时定位无效
        int span = 2000;
        mOption.setScanSpan(span);
        //设置 LocationClientOption
        mylocationClient.setLocOption(mOption);

        myOrientationListener = new MyOrientationListener(GradeActivity.this);
    }
    /*
     *定位请求回调接口
     */
    public class MylocationListener implements BDLocationListener {
        //定位请求回调函数,这里面会得到定位信息
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //BDLocation 回调的百度坐标类，内部封装了如经纬度、半径等属性信息
            //MyLocationData 定位数据,定位数据建造器
            /*
             * 可以通过BDLocation配置如下参数
             * 1.accuracy 定位精度
             * 2.latitude 百度纬度坐标
             * 3.longitude 百度经度坐标
             * 4.satellitesNum GPS定位时卫星数目 getSatelliteNumber() gps定位结果时，获取gps锁定用的卫星数
             * 5.speed GPS定位时速度 getSpeed()获取速度，仅gps定位结果时有速度信息，单位公里/小时，默认值0.0f
             * 6.direction GPS定位时方向角度
             * */
            count++;
//            Log.e("==位置==",bdLocation.getProvince()+"-"+bdLocation.getCity()+"-"+bdLocation.getDistrict()+"-"+bdLocation.getStreet());
            if(!TextUtils.isEmpty(bdLocation.getProvince())&&!TextUtils.isEmpty(bdLocation.getCity())&&!TextUtils.isEmpty(bdLocation.getDistrict())){
                Arad.preferences.putString(Config.PROVINCE, bdLocation.getProvince()).flush();
                Arad.preferences.putString(Config.CITY, bdLocation.getCity()).flush();
                Arad.preferences.putString(Config.AREA, bdLocation.getDistrict()).flush();
                if(selectLocation){
                    return;
                }else{
                    pro=bdLocation.getProvince();
                    city=bdLocation.getCity();
                    area=bdLocation.getDistrict();
                    tvSelectCity.setText(bdLocation.getProvince()+bdLocation.getCity()+bdLocation.getDistrict());
                }
            }
//            if(null!=bdLocation.getCity()){
//                String city=Arad.preferences.getString("cityInfo");
//                if(TextUtils.isEmpty(city)){
//                    Logg.e("==获取城市-保存城市===");
//                    Arad.preferences.putString("cityInfo", bdLocation.getCity()).flush();
//                }
//                if(!city.equals(bdLocation.getCity())){
//                    Arad.preferences.putString("cityInfo", bdLocation.getCity()).flush();
//                }
//            }
        }
    }
    /*
     *定位服务的生命周期，达到节省
     */
    @Override
    protected void onStart() {
        super.onStart();
        //开启定位，显示位置图标
        if(!mylocationClient.isStarted()){
            mylocationClient.start();
        }
        myOrientationListener.start();
    }
    @Override
    protected void onStop() {
        super.onStop();
        mylocationClient.stop();
        myOrientationListener.stop();
    }
}
